package com.itheima.utils;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
 * Mapper抽取工具类：
 *   mapper接口对象
 * */
public class MapperUtil {

    private MapperUtil(){}

    //直接获取Mapper代理对象
    public static <T> T getMapper(Class<T> tClass){
        final SqlSession session=getSession();
        final T mapper = session.getMapper(tClass);
        T mapperProxy=(T)Proxy.newProxyInstance(mapper.getClass().getClassLoader(), mapper.getClass().getInterfaces(), new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                Object obj=null;
                try {
                    obj= method.invoke(mapper,args);
                }catch (Exception e){}
                /*finally {
                    if (session!=null){
                        session.commit();
                        session.close();
                    }
                }*/
                return obj;
            }
        });

        return mapperProxy;
    }


    //声明一个获取SqlSession方法
    public static SqlSession getSession(){
        //1、读取核心配置文件
        SqlSession session =null;
        try {
            InputStream is = null;
            is = Resources.getResourceAsStream("sql.xml");
            //2、构建SqlSessionFactory对象
            SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
            //3、获取SqlSession对象
            session = factory.openSession();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return session;
    }


   /* public static void close(SqlSession session){
        if (session!=null){
            session.commit();
            session.close();
        }
    }*/





}

